package com.example.controller;

import com.example.model.DbConnection;
import com.example.service.DbConnectionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/db-connections")
public class DbConnectionController {
    
    private static final Logger log = LoggerFactory.getLogger(DbConnectionController.class);
    
    @Autowired
    private DbConnectionService dbConnectionService;
    
    /**
     * 获取当前用户的所有数据库连接
     */
    @GetMapping
    public ResponseEntity<List<DbConnection>> getUserConnections(@RequestAttribute Long userId) {
        log.info("获取用户数据库连接列表，用户ID: {}", userId);
        List<DbConnection> connections = dbConnectionService.getUserConnections(userId);
        log.info("获取用户数据库连接列表成功，用户ID: {}，连接数量: {}", userId, connections.size());
        return ResponseEntity.ok(connections);
    }
    
    /**
     * 获取用户的默认数据库连接
     */
    @GetMapping("/default")
    public ResponseEntity<?> getDefaultConnection(@RequestAttribute Long userId) {
        log.info("获取用户默认数据库连接，用户ID: {}", userId);
        DbConnection connection = dbConnectionService.getDefaultConnection(userId);
        if (connection != null) {
            log.info("获取用户默认数据库连接成功，用户ID: {}，连接ID: {}", userId, connection.getId());
            return ResponseEntity.ok(connection.withoutPassword());
        } else {
            log.info("用户未设置默认数据库连接，用户ID: {}", userId);
            Map<String, String> response = new HashMap<>();
            response.put("message", "未设置默认数据库连接");
            return ResponseEntity.ok(response);
        }
    }
    
    /**
     * 获取指定ID的数据库连接
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getConnection(@PathVariable Long id, @RequestAttribute Long userId) {
        log.info("获取指定数据库连接，用户ID: {}，连接ID: {}", userId, id);
        try {
            DbConnection connection = dbConnectionService.getConnectionById(id, userId);
            log.info("获取指定数据库连接成功，用户ID: {}，连接ID: {}", userId, id);
            return ResponseEntity.ok(connection.withoutPassword());
        } catch (Exception e) {
            log.error("获取指定数据库连接失败，用户ID: {}，连接ID: {}", userId, id, e);
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 创建新的数据库连接
     */
    @PostMapping
    public ResponseEntity<?> createConnection(@RequestBody DbConnection connection, @RequestAttribute Long userId) {
        log.info("创建新数据库连接，用户ID: {}，连接名称: {}, 数据库类型: {}", 
                userId, connection.getName(), connection.getDbType());
        try {
            connection.setUserId(userId);
            DbConnection createdConnection = dbConnectionService.createConnection(connection);
            log.info("创建新数据库连接成功，用户ID: {}，连接ID: {}", userId, createdConnection.getId());
            return ResponseEntity.ok(createdConnection);
        } catch (Exception e) {
            log.error("创建新数据库连接失败，用户ID: {}，连接名称: {}", userId, connection.getName(), e);
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新数据库连接
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateConnection(
            @PathVariable Long id, 
            @RequestBody DbConnection connection, 
            @RequestAttribute Long userId) {
        log.info("更新数据库连接，用户ID: {}，连接ID: {}", userId, id);
        try {
            connection.setId(id);
            connection.setUserId(userId);
            DbConnection updatedConnection = dbConnectionService.updateConnection(connection, userId);
            log.info("更新数据库连接成功，用户ID: {}，连接ID: {}", userId, id);
            return ResponseEntity.ok(updatedConnection);
        } catch (Exception e) {
            log.error("更新数据库连接失败，用户ID: {}，连接ID: {}", userId, id, e);
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 删除数据库连接
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteConnection(@PathVariable Long id, @RequestAttribute Long userId) {
        log.info("删除数据库连接，用户ID: {}，连接ID: {}", userId, id);
        try {
            dbConnectionService.deleteConnection(id, userId);
            log.info("删除数据库连接成功，用户ID: {}，连接ID: {}", userId, id);
            Map<String, String> response = new HashMap<>();
            response.put("message", "数据库连接已删除");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除数据库连接失败，用户ID: {}，连接ID: {}", userId, id, e);
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 设置默认数据库连接
     */
    @PutMapping("/{id}/default")
    public ResponseEntity<?> setDefaultConnection(@PathVariable Long id, @RequestAttribute Long userId) {
        log.info("设置默认数据库连接，用户ID: {}，连接ID: {}", userId, id);
        try {
            dbConnectionService.setDefaultConnection(id, userId);
            log.info("设置默认数据库连接成功，用户ID: {}，连接ID: {}", userId, id);
            Map<String, String> response = new HashMap<>();
            response.put("message", "已设置为默认连接");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("设置默认数据库连接失败，用户ID: {}，连接ID: {}", userId, id, e);
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 测试数据库连接
     */
    @PostMapping("/test")
    public ResponseEntity<?> testConnection(@RequestBody DbConnection connection) {
        log.info("测试数据库连接，连接名称: {}，数据库类型: {}, 主机: {}, 端口: {}",
                connection.getName(), connection.getDbType(), connection.getHost(), connection.getPort());
        try {
            dbConnectionService.testConnection(connection);
            log.info("测试数据库连接成功，连接名称: {}", connection.getName());
            Map<String, String> response = new HashMap<>();
            response.put("message", "连接测试成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("测试数据库连接失败，连接名称: {}", connection.getName(), e);
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 